Given an array and chunk size, divide the array into many subarrays where each subarray is of length size
chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]
Two solutions: 1. Iterative
2. Use Array.prototype.slice()
function chunk(array, size) {
let chunked = [];
let idx = 0;
while (idx < array.length){
chunked.push(array.slice(idx, size + idx));
idx += size;
}
return chunked;
}
function chunk(array, size) {
let chunked = [];
for (let element of array){
let last = chunked[chunked.length - 1];
if (!last || last.length === size){
chunked.push([element]);
} else {
last.push(element);
}
}
return chunked;
}
chunk([1, 2, 3, 4], 2)
chunk([1, 2, 3, 4, 5], 2)
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3)
chunk([1, 2, 3, 4, 5], 4)
chunk([1, 2, 3, 4, 5], 10)